﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SuperX.Common.Helper
{
    //
    public static class GenerateUid
    {
        /// <summary>
        /// 生成唯一GUID
        /// </summary>
        /// <returns></returns>
        public static Guid GenerateGuid()
        {
            return Guid.NewGuid();
        }

        /// <summary>
        /// 为了解决UUID不可读，可以使用UUID to Int64的方法
        /// </summary>
        /// <returns></returns>
        public static long GenerateGuidToInt64()
        {
            return BitConverter.ToInt64(Guid.NewGuid().ToByteArray(), 0);
        }

        /// <summary>
        /// Generate a new <see cref="Guid"/> using the comb algorithm.
        /// 为了解决UUID无序的问题，NHibernate在其主键生成方式中提供了Comb算法（combined guid/timestamp）。
        /// 保留GUID的10个字节，用另6个字节表示GUID生成的时间（DateTime）。
        /// </summary>
        public static Guid GenerateComb()
        {
            byte[] array = Guid.NewGuid().ToByteArray();
            DateTime dateTime = new DateTime(1900, 1, 1);
            DateTime now = DateTime.Now;
            TimeSpan timeSpan = new TimeSpan(now.Ticks - dateTime.Ticks);
            TimeSpan timeOfDay = now.TimeOfDay;
            byte[] bytes = BitConverter.GetBytes(timeSpan.Days);
            byte[] bytes2 = BitConverter.GetBytes((long)(timeOfDay.TotalMilliseconds / 3.333333));
            Array.Reverse(bytes);
            Array.Reverse(bytes2);
            Array.Copy(bytes, bytes.Length - 2, array, array.Length - 6, 2);
            Array.Copy(bytes2, bytes2.Length - 4, array, array.Length - 4, 4);
            return new Guid(array);
        }

        /// <summary>
        /// 采用雪花漂移算法生成唯一Int64
        /// </summary>
        /// <returns></returns>
        public static long GenerateSnowFlake()
        {
            return GenerateUid.IdWorker.NextId();
        }

        //
        private static readonly IdFactory IdWorker = new IdFactory(0L, 0L);
    }
}